import React from 'react';
import { Input, Icon } from 'antd'

import ListSelector from 'components/list-selector'
import {messages} from "share/common";

/**
 * 列表选择输入表单组件，由antd的Input组件改造而来,Input + listSelector的自定义表单组件
 *
 * 2018/11/26 zaranengap
 * 这货就是个Input + listSelector的结合
 * 到现在只有一个地方用了这货
 * 借款单还款12月也用到了
 * 产品根本不知道有这个玩意
 * 知道了也不会用这个东西设计
 * So why i wrote this?
 *
 */
class Inputter extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: '',
      showListSelector: false
    };
  }

  handleListCancel = () => {
    this.setState({ showListSelector: false })
  };

  //默认值，可控组件
  componentWillReceiveProps(nextProps) {
    if ('value' in nextProps) {
      const value = nextProps.value;
      this.setState({value});
    }
  }

  /**
   * ListSelector确认点击事件，返回的结果根据valueKey赋值
   * @param result
   */
  handleListOk = (result) => {
    if(result.result.length > 0){
      let value = result.result[0][this.props.valueKey];
      this.setState({ value });
      //手动调用onChange事件以与父级Form绑定
      this.onChange(value);
    }
    this.setState({ showListSelector: false },() => {
      this.props.onOk(result);
    });
  };

  onChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  render() {
    const { showListSelector, value } = this.state;
    const { placeholder, disabled, selectorItem, type, listExtraParams, valueKey } = this.props;
    return (
      <div className="inputter">
        <Input
          onChange={(e) => {this.setState({value: e.target.value});this.onChange(e.target.value)}}
          value={value}
          placeholder={placeholder}
          disabled={disabled}
          addonAfter={<Icon type="ellipsis" style={{cursor: 'pointer'}} onClick={() => {this.setState({ showListSelector: !disabled})}}/>}
        />
        <ListSelector
          visible={showListSelector}
          type={type}
          valueKey={valueKey}
          onCancel={this.handleListCancel}
          onOk={this.handleListOk}
          extraParams={listExtraParams}
          selectorItem={selectorItem}
          single
        />
      </div>
    );
  }
}

Inputter.propTypes = {
  placeholder: React.PropTypes.string,  //输入框空白时的显示文字
  disabled: React.PropTypes.bool,  //是否可用
  type: React.PropTypes.string,  //list选择的type，参见chooserData内
  selectorItem: React.PropTypes.object,  //listSelector的selectorItem
  valueKey: React.PropTypes.string,  //所需要的变量名
  listExtraParams: React.PropTypes.object,  //listSelector的额外参数
  onChange: React.PropTypes.func,  //进行选择后的回调
  value: React.PropTypes.string,  //显示的值
  onOk: React.PropTypes.func //list选择后的回调
};

Inputter.defaultProps = {
  placeholder: `${messages('common.please.enter')/*请输入*/} / ${messages('common.please.select')/*请选择*/}`,
  disabled: false,
  listExtraParams: {},
  onOk: () => {}
};

export default Inputter;
